package com.alarmgame;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;

import com.alarmgame.service.AlarmGameService;

public class AlarmGameActivity extends Activity {
    /** Called when the activity is first created. */   
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
	public void pickTimeHandler(View target) {
		//Toast.makeText(AlarmGameActivity.this, "in  PickTimehandler", Toast.LENGTH_LONG).show();
		showDialog(0);
	}

	protected Dialog onCreateDialog(int id) {
		//Toast.makeText(AlarmGameActivity.this, " - onCreateDialog(ID_TIMEPICKER) - ", Toast.LENGTH_LONG).show();
		final Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		return new TimePickerDialog(this, theTimeSetListener, hour, minute, false);
	}

	private TimePickerDialog.OnTimeSetListener theTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hour, int minute) {
			String time = "Hora: " + String.valueOf(hour) + "\n" + "Minuto: " + String.valueOf(minute);
			Toast.makeText(AlarmGameActivity.this, time, Toast.LENGTH_LONG).show();
			int theHour = hour;
			int theMinute = minute;

			Intent alarmServiceIntent = new Intent(getBaseContext(), AlarmGameService.class);		
			PendingIntent pendingAlarmIntent = PendingIntent.getService(getBaseContext(), 0, alarmServiceIntent, 0);			
			AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

			Calendar alarmCal = Calendar.getInstance();
			alarmCal.setTimeInMillis(System.currentTimeMillis());
			alarmCal.set(Calendar.HOUR_OF_DAY, theHour); // set user selection
			alarmCal.set(Calendar.MINUTE, theMinute); // set user selection
			alarmCal.set(Calendar.SECOND, 0);		
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingAlarmIntent);
			finish();
		}
	};
}